#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QString>
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QJsonDocument>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //进行初始化工作
    mode = 1;
    maxNumber = 100;
    ui->radAdd->setChecked(true);

    loadFile();

    updateData();

}

MainWindow::~MainWindow()
{
    delete ui;
}

//更新数据
void MainWindow::updateData()
{
    string s = "";

    for(int i = 0;i < idArray.size();i++)
    {
        s += to_string(idArray[i]);
        s += " ";
        s += nameArray[i];
        s += "\n";
    }
    ui->textEdit->setPlainText("");
    ui->textEdit->setPlainText(QString::fromStdString(s));
}
//加载文件
void MainWindow::loadFile()
{
    QFile file("data.json");
    if (!file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        qDebug()<<"Fail";
        return;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonData);
    if (jsonDocument.isNull())
    {
        qDebug()<< "Fail";
        return;
    }
    QJsonObject jsonObject = jsonDocument.object();
    int num = jsonObject["count"].toInt();

    //得到 items
    QJsonArray itemsArray = jsonObject["items"].toArray();

    //读取数据到items
    for(int i = 0;i < itemsArray.size();i++)
    {
        QJsonValue itemValue = itemsArray.at(i);
        if (itemValue.isObject())
        {
            QJsonObject itemObject = itemValue.toObject();

            //读取数据
            int id = itemObject["ID"].toInt();
            QString name = itemObject["Name"].toString();

            idArray.push_back(id);
            nameArray.push_back(name.toStdString());
        }
    }


}
//查找信息
int MainWindow::findDataById(int id)
{

    for (int i =0; i < idArray.size();i++)
    {
        if (idArray[i] == id)
        {
            return i;
        }
    }
    return -1;
}

//槽函数：确定按钮被按下
void MainWindow::on_btnOk_clicked()
{
    int id;
    string name;
    int pos;
    bool conversionOK;

    switch (mode)
    {
        case 1://添加
            {
                //1 判断数据是否合理
                if (ui->lineEditID->text().isEmpty())
                {
                    QMessageBox::information(nullptr,"Tips","ID不能为空");
                    return;
                }
                else if (ui->lineEditName->text().isEmpty())
                {
                    QMessageBox::information(nullptr,"Tips","Name不能为空");
                    return;
                }
                else if (idArray.size() > maxNumber)
                {
                    QMessageBox::information(nullptr,"Tips","up");
                    return;
                }
                id = ui->lineEditID->text().toInt(&conversionOK);
                if (findDataById(id) != -1)//查找是否有相同ID号的
                {
                    QMessageBox::information(nullptr,"Tips","该会员已经存在！");
                    return;
                }
                name = ui->lineEditName->text().toStdString();
                //2 将数据存入容器中
                idArray.push_back(id);
                nameArray.push_back(name);
                //3 更新数据，并写入文件中
                updateData();
                //4 打印成功添加信息
                QMessageBox::information(nullptr,"Tips","添加成功!");
                //5 将显示文本清空
                ui->lineEditID->text() = "";
                ui->lineEditName->text() = "";
                break;
            }
        case 2://删除
        {
            //1 判断数据是否合理
            if (ui->lineEditID->text().isEmpty())
            {
                QMessageBox::information(nullptr,"Tips","ID不能为空");
                return;
            }
            //2 获取要删除的ID号
            id = ui->lineEditID->text().toInt(&conversionOK);
            pos = findDataById(id);
            if (pos == -1)
            {
                QMessageBox::information(nullptr,"Tips","ID no ");
                return;
            }
            //3 删除对应容器下的数据
            idArray.erase(idArray.begin() + pos);
            nameArray.erase(nameArray.begin() + pos);
            //4 更新数据，写入文件中
            updateData();
            //5 打印提示信息
            QMessageBox::information(nullptr,"Tips","删除成功");
            break;
        }
        case 3://更新
        {
            //1 判断数据是否合理
            if (ui->lineEditID->text().isEmpty())
            {
                QMessageBox::information(nullptr,"Tips","ID不能为空");
                return;
            }
            else if (ui->lineEditName->text().isEmpty())
            {
                QMessageBox::information(nullptr,"Tips","Name不能为空");
                return;
            }
            //2 获取要更新的ID号
            id = ui->lineEditID->text().toInt(&conversionOK);
            pos = findDataById(id);
            if (pos == -1)
            {
                QMessageBox::information(nullptr,"Tips","ID no");
                return;
            }
            //3 更新对应容器下的数据
            name = ui->lineEditName->text().toStdString();
            nameArray[pos] = name;
            //4 更新数据，写入文件中
            updateData();
            //5 打印提示信息
            QMessageBox::information(nullptr,"Tips","更新成功");
            break;
        }
        case 4://查询
        {
            //1 判断数据是否合理
            if (ui->lineEditID->text().isEmpty())
            {
                QMessageBox::information(nullptr,"Tips","ID不能为空");
                return;
            }
            //2 获取要查询的ID号
            id = ui->lineEditID->text().toInt(&conversionOK);
            pos = findDataById(id);
            if (pos == -1)
            {
                QMessageBox::information(nullptr,"Tips","ID no");
                return;
            }
            //3 获取要查询的名字
            name = nameArray[pos];
            //4 打印查询信息
            QMessageBox::information(nullptr,"Tips",QString::fromStdString(string("名字为 ") + name));
            //5 将显示文本清空
            ui->lineEditID->text() = "";
            ui->lineEditName->text() = "";
            break;
        }
    }
}

//槽函数：取消按钮被按下
void MainWindow::on_btnCancel_clicked()
{
    this->close();
}

//槽函数：保存按钮被按下
void MainWindow::on_btnSave_clicked()
{
    QJsonArray itemsArray;
    //1 保存信息到itemsArray中
    for(int i =0; i < idArray.size();i++)
    {
        /*
在 Qt 中，QJsonObject 是用于表示 JSON 对象的类。它可以用来创建、解析和操作 JSON 格式的数据。
如果你创建了一个 QJsonObject 对象，可以使用一系列方法来添加、修改、访问和删除 JSON 对象中的键值对。
*/
        QJsonObject itemObject;
        itemObject["ID"] = idArray[i];
        itemObject["Name"] = QString::fromStdString(nameArray[i]);
        itemsArray.append(itemObject);
    }
    //2 创建jsonObject
    QJsonObject jsonObject;
    jsonObject["count"] = itemsArray.size();
    jsonObject["items"] = itemsArray;
    //3 创建jsonDocument
    QJsonDocument jsonDocument(jsonObject);
    //3 保存信息到json文件
    QFile file("data.json");
    if (file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        file.write(jsonDocument.toJson());
        file.close();
        QMessageBox::information(nullptr,"Tips","Successfully");
    }
    else
    {
        qDebug()<<"Fail";
    }
}




void MainWindow::on_radAdd_toggled(bool checked)
{
    if (checked)
    {
        this->mode = 1;
    }
}


void MainWindow::on_radDel_toggled(bool checked)
{
    if (checked)
    {
        this->mode = 2;
    }
}

void MainWindow::on_radUp_toggled(bool checked)
{
    if (checked)
    {
        this->mode = 3;
    }
}


void MainWindow::on_radSer_toggled(bool checked)
{
    if (checked)
    {
        this->mode = 4;
    }
}

